package com.oyjd.framework.util;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import com.oyjd.framework.Const;
import com.oyjd.framework.log.MyLog;

/**
 * 支持图片控件异步加载网络图片和缓存图片
 * 
 * @author 欧建东
 * @email oyjd@163.com
 * 
 */
public class ImageHelp {
	private static Map<String, List<ImageView>> map = new HashMap<String, List<ImageView>>();

	/**
	 * 图片加载处理
	 * 
	 * @param img
	 *            图片控件
	 * @param url
	 *            图片网络地址
	 */
	public static void doImg(ImageView img, String url) {
		String path = getImgNameByUrl(url);
		if (new File(path).exists()) {
			Drawable d = Drawable.createFromPath(path);
			img.setImageDrawable(d);
		} else {
			if (map.containsKey(url)) {
				map.get(url).add(img);
			} else {
				List<ImageView> t = new ArrayList<ImageView>();
				t.add(img);
				map.put(url, t);
				pool.execute(new MyTemp(url));
			}
		}
	}

	/**
	 * 线程池
	 */
	private static ExecutorService pool = new ThreadPoolExecutor(3, 5, 0L, TimeUnit.NANOSECONDS, new LinkedBlockingQueue<Runnable>());

	/**
	 * 消息处理
	 */
	private static Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			String url = (String) msg.obj;
			switch (msg.arg1) {
			case 0:// 加载成功
				List<ImageView> t = map.get(url);
				String path = getImgNameByUrl(url);
				Drawable d = Drawable.createFromPath(path);
				for (ImageView img : t) {
					if (img != null)
						img.setImageDrawable(d);
				}
				break;
			default:// 加载失败

				break;
			}
			map.remove(url);
		}
	};

	/**
	 * 内部临时线程
	 * 
	 * @author <b>欧建东<br/>
	 *         Email:oyjd@163.com</b>
	 * @version 1.0
	 * 
	 */
	private static class MyTemp implements Runnable {

		private String url;

		public MyTemp(String url) {
			super();
			this.url = url;
		}

		public void run() {
			Message msg = new Message();
			msg.obj = url;
			try {
				byte[] data = HttpNet.getBytesFromNet(url);
				FileOP.writeFile(getImgNameByUrl(url), data);
				msg.arg1 = 0;
			} catch (Exception e) {
				msg.arg1 = 1;
				MyLog.e("ImageHelp", e.getMessage(), e);
			}
			handler.sendMessage(msg);
		}
	}

	/**
	 * 获取唯一的图片路径
	 * 
	 * @param url
	 * @return
	 */
	private static String getImgNameByUrl(String url) {
		String ex = ".jpg";
		int p = url.lastIndexOf(".");
		if (-1 != p) {
			String t = url.substring(p + 1);
			if (t.equalsIgnoreCase("png")) {
				ex = ".png";
			} else if (t.equalsIgnoreCase("gif")) {
				ex = ".gif";
			}
		}
		return Const.APP_IMG_DIR + "img_" + url.hashCode() + ex;
	}

}
